package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"weekly-report/tools"
	"weekly-report/types"

	"github.com/firebase/genkit/go/ai"
	"github.com/firebase/genkit/go/genkit"
	"github.com/firebase/genkit/go/plugins/googlegenai"
)

func main() {
	ctx := context.Background()

	// 初始化 Genkit
	g := genkit.Init(ctx,
		genkit.WithPlugins(&googlegenai.GoogleAI{}),
		genkit.WithDefaultModel("googleai/gemini-2.5-pro"),
	)

	// 注册工具
	genkit.DefineTool(g, "getGitSummary", "获取Git提交摘要", func(ctx *ai.ToolContext, report types.WeeklyInput) (string, error) {
		return tools.GetGitSummary(ctx, report.RepoPath)
	})
	genkit.DefineTool(g, "summarizeDocs", "获取Doc文档摘要", func(ctx *ai.ToolContext, report types.WeeklyInput) (string, error) {
		return tools.SummarizeDocs(ctx, g, report.DocPath)
	})
	genkit.DefineTool(g, "getExcelSummary", "获取Excel工作文档摘要", func(ctx *ai.ToolContext, report types.WeeklyInput) (string, error) {
		return tools.GetExcelSummary(ctx, report.ExcelPath)
	})
	genkit.DefineTool(g, "exportMarkdown", "导出Markdown格式的周报", func(ctx *ai.ToolContext, report types.WeeklyReport) (string, error) {
		return tools.ExportMarkdown(ctx, &report)
	})

	// 定义主 Flow
	reportFlow := genkit.DefineFlow(g, "generateWeeklyReport",
		func(ctx context.Context, input types.WeeklyInput) (*types.WeeklyReport, error) {
			repoSum, _ := tools.GetGitSummary(ctx, input.RepoPath)
			excelSum, _ := tools.GetExcelSummary(ctx, input.ExcelPath)

			docSum := input.DocsSummary
			if docSum == "" {
				// 自动生成文档摘要
				autoSum, err := tools.SummarizeDocs(ctx, g, "./docs") // 这里可以改成 input.DocPath
				if err == nil {
					docSum = autoSum
				}
			}

			prompt := fmt.Sprintf(`
请根据以下内容生成本周工作周报，输出结构化 JSON。
【代码提交】
%s
【工作文档】
%s
【统计数据】
%s
字段包括：
- week
- summary
- keyAchievements
- issues
- nextWeekPlan
`, repoSum, docSum, excelSum)

			week := time.Now().Format("2006-01-02")

			report, _, err := genkit.GenerateData[types.WeeklyReport](ctx, g, ai.WithPrompt(prompt))
			if err != nil {
				return nil, err
			}

			report.Week = week

			_, _ = tools.ExportMarkdown(ctx, report)
			return report, nil
		})

	// HTTP 服务
	http.HandleFunc("/weekly", genkit.Handler(reportFlow))
	log.Println("Server started on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
